<?php
class Admin_Model_Users extends TBB_Model_Users
{	
	/**
	 * Create user (only used for admin module)
	 * @param string $username
	 * @param string $password
	 * @param int $customerID
	 * @param array $roleIDs
	 * @return int
	 */
	public function createUserAccount($username, $password, $customerID = null, $roleIDs = array())
	{
		$db = Zend_Db_Table::getDefaultAdapter();
		$db->beginTransaction();
		try {			
			// first create user
			$userID = $this->_createUser($username, $password, $customerID);
			
			// second create roles for the user
			$this->_createRolesForUser($userID, $roleIDs);
			
			$db->commit();			
			return userID;
		} catch(Exception $e) {
			$db->rollback();
			throw $e;
		}		
	}
	
	/**
	 * Update role of user
	 * @param int $newRoles $newRoles has form Array([11] => 1, [12] => 0, ..., [n] => m)) with n is role ID and m is checked/unchecked
	 * @param int $userID 
	 * @return bool
	 */
	public function updateRolesOfUser($roleIDs, $userID) 
	{		
		// get old roles
		$oldRoles = $this->getRolesOfUser($userID);
		
		// extract old role ID except "customer role ID"
		$roleModel = new Admin_Model_Role();
		$customerRoleID = $roleModel->getCustomerRoleID();
		$oldRoleIDs = array();
		foreach($oldRoles as $oldRole) {
			if($oldRole['role_id'] != $customerRoleID) {
				$oldRoleIDs[] = $oldRole['role_id'];
			}
		}
	
		// assign $roleIDs to $newRoleIDs;
		$newRoleIDs = $roleIDs;
		
		$db = Zend_Db_Table::getDefaultAdapter();
		$db->beginTransaction();		
		try {
			// following the algorithm, we have oldRoleIDs as A, newRoleIDs as B
			foreach($oldRoleIDs as $index => $id) {
				if(!in_array($id, $newRoleIDs)) {
					$this->deleteRoleOfUser($id, $userID);
					unset($oldRoleIDs[$index]);
				}
			}
			
			foreach($newRoleIDs as $id) {
				if(!in_array($id, $oldRoleIDs)) {
					$this->insertRoleOfUser($id, $userID);
				}
			}
			
			$db->commit();
			return true;
		} catch(Zend_Exception $e) {						
			$db->rollBack();
			return false;
		}		
	}
	
	/**
	 * Delete role of user (helper)
	 * @param int $roleID
	 * @param int $userID
	 * @return int
	 */
	private function deleteRoleOfUser($roleID, $userID)
	{		
		$db = Zend_Db_Table::getDefaultAdapter();
		return $db->delete('user2role', "user_id = '$userID' AND role_id = '$roleID'");		
	}

	/**
	 * insert role of user (helper)
	 * @param int $roleID
	 * @param int $userID
	 * @return int
	 */
	private function insertRoleOfUser($roleID, $userID) {
		$db = Zend_Db_Table::getDefaultAdapter();
		return $db->insert('user2role', array('user_id' => $userID,
											  'role_id' => $roleID));
	}
}